<template>
	<view>
		<view class="canvasBox">
			<canvas type="2d" id="imageCanvasHide" canvas-id="imageCanvasHide" class="canvasHide"
				disable-scroll="true" />

			<canvas type="2d" id="imageCanvas" canvas-id="imageCanvas" class="imageCanvas" disable-scroll="true"
				@touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd" />
		</view>
		<view class="text-center" style="letter-spacing: 15rpx; font-weight: bold; margin: 30rpx 0">单指拖动/双指缩放</view>
		<view style="background-color: #efefef; border-radius: 20rpx; margin: 0 20rpx">

			<view style="display: flex; flex-wrap: wrap; margin-left: 22rpx">
				<view class="btn" @click="rotateRight(90)">旋转</view>
				<view v-for="(item, index) in filtersList" :key="index" class="btn" @click="selectFilters(item.type)">
					{{ item.label }}
				</view>
				<!-- <view class="btn" @click="resetCanvas">原图</view> -->
				<view class="btn" @click="resetImage">原图</view>
			</view>
		</view>
		<view style="
        background-color: #efefef;
        border-radius: 20rpx;
        margin: 35rpx 20rpx;
        padding-top: 1rpx;
      ">
			<view class="connect-box" style="padding-top: -20rpx">
				<view class="connect-box-state" @click="gblink()">断开连接</view>
				<view class="connect-box-select-device"
					:style="{ 'color': linkname.name == '需先点这里连接影描机' ? 'red' : '#333', 'font-weight': '600' }"
					@click="selecttype()">{{
						linkname.name
					}}</view>
			</view>

			<view class="flex justify-around">
				<view class="btn2" @click="checkImage">相册导入</view>
				<view class="btn2" @click="saveImage()">保存相册</view>
			</view>

			<view class="flex justify-around">
				<view :class="['btn2', { sending: isSending }]" @tap="sendImage" :disabled="isSending">开始投图（直投）</view>
				<!-- 		<view class="btn2" @tap="resetFileTranse">复位远端</view> -->
				<!--				<view class="btn2" @tap="proportionalcalculation">等比计算</view>-->
				<view :class="['btn2', { sending: isSending1 }]" @tap="toCorrectionPage()" :disabled="isSending1">校正投图（侧投）
				</view>
			</view>
		</view>

		<blue-link :show="showBlueLinkDialog" @close="closeblue()" :wifiInfo="wifiInfo.ssid" :istype="istype" />

		<compress ref="helangCompress" />

		<uni-popup ref="popup" title="选择连接方式" backgroundColor="white" :safeArea="false" type="bottom">

			<view class="box m-20 p-15-10 h-300" @click="startBlue(true)">
				<view class="title600">WIFI模式投图</view>
				<view class="p-15-10">1:请检查影描机是否连接WIFI(需和手机同一个2.4G网络)</view>
				<view class="p-15-10">
					<text>2:当前手机连接WIFI名称：</text>
					<text style="color: #e43d33">
						{{ wifiInfo.ssid ? wifiInfo.ssid : "未连接" }}
					</text>
				</view>
				<view class="p-15-10">3:请检查影描机是否被连接占用</view>
			</view>
			<view class="box m-20 p-15-10 h-300" @click="startBlue(false)">
				<view class="title600">蓝牙模式投图</view>
				<div style="
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 260rpx;
          ">
					<view class="p-15-10">1:请检查手机是否打开蓝牙</view>
					<view class="p-15-10">2:请检查影描机是否被连接占用</view>
				</div>
			</view>
		</uni-popup>

		<uni-popup ref="popup1" title="等比计算" backgroundColor="white" :safeArea="false" type="bottom">
			<view class="title600" style="font-size: 18px; padding-top: 10px">图片不变形纸张尺寸计算表</view>

			<view class="box m-20 p-20" style="display: flex">
				<view class="p-20 titlebor6" v-if="imgSize">原图尺寸</view>
				<view class="p-20" v-if="imgSize" style="padding-left: 0">宽:{{ imgSize.width.toFixed(0) }}</view>
				<view class="p-20" v-if="imgSize">高:{{ imgSize.height.toFixed(0) }}</view>
			</view>
			<view class="box m-20 p-20">
				<view style="
            display: flex;
            justify-items: center;
            align-items: center;
            margin-bottom: 20rpx;
          ">
					<view class="titlebor6 p-20">纸张宽度</view>
					<input class="inputwifi" v-model="isk" @input="updateHeight" type="number" placeholder="请填写宽度" />
				</view>
				<view style="display: flex; justify-items: center; align-items: center">
					<view class="titlebor6 p-20">纸张高度</view>
					<input class="inputwifi" v-model="ish" @input="updateWidth" type="number" placeholder="请填写高度" />
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import BlueLink from "@/components/BlueLink1.vue";
import Compress from "@/components/compress.vue";
import {
	Blue
} from "@/utils/index.js";
var dpr = uni.getSystemInfoSync().pixelRatio;
var canvas, canvas2;
var ctx, ctx2;
var image, image2;
var imgData, imgData2, canvas2data;
export default {
	components: {
		BlueLink,
		Compress,
	},
	data() {
		return {
			isbu: true,
			updatingField: "",
			isk: "", // 用户输入的宽度
			ish: "", // 用户输入的高度
			isSending: false,
			isSending1: false,
			istype: false,
			showBlueLinkDialog: false,
			filtersList: [{
				type: "1",
				label: "黑白",
			},
			{
				type: "2",
				label: "上下翻转",
			},
			{
				type: "3",
				label: "左右翻转",
			},
			{
				type: "4",
				label: "缩小",
			},
			{
				type: "5",
				label: "放大",
			},
			{
				type: "6",
				label: "线稿",
			},
			],
			imageSrc: "",
			imageInfo: {
				src: "",
			},
			canvasStyle: {
				width: 1280,
				height: 720,
			},
			imgSize: {
				left: 0,
				top: 0,
				width: 0,
				height: 0,
			},
			canvasRadio: 0, // 缩放比例
			rotateX: 0, // 垂直翻转角度
			rotateY: 0, // 水平翻转角度
			rotateAll: 0, // 旋转角度

			isFirstInit: true,
			touchStartX: 0,
			touchStartY: 0,
			touchMoveX: 0,
			touchMoveY: 0,
			touchStartScale: 1,
			touchCurrentScale: 1,
			touchStartDist: 0,
			touchCurrentDist: 0,
			touchStartPoint1: {
				x: 0,
				y: 0,
			},
			touchStartPoint2: {
				x: 0,
				y: 0,
			},
			touchCurrentPoint1: {
				x: 0,
				y: 0,
			},
			touchCurrentPoint2: {
				x: 0,
				y: 0,
			},
			isDragging: false,
			isScaling: false,
			scaleMultiplier: 1,
			lastMoveTime: 0,
			gotoname: "",
			bluename: "",
			wifissid: "",
			linkname: {
				name: "需先点这里连接影描机",
			},
			canvas2data: "",
			wifiInfo: {
				ssid: "",
			},
			isFilterBlack: false,
		};
	},
	watch: {
		// isk(newVal) {
		// 	if (newVal) {
		// 		this.ish = (newVal / this.imgSize.width * this.imgSize.height).toFixed(0);
		// 	}
		// },
		// ish(newVal) {
		// 	if (newVal) {
		// 		this.isk = (newVal / this.imgSize.height * this.imgSize.width).toFixed(0);
		// 	}
		// }
	},
	mounted() {
		uni.getSetting({
			success: (res) => {
				console.log(res.authSetting);

				if (!res.authSetting["scope.writePhotosAlbum"]) {
					uni.authorize({
						scope: "scope.writePhotosAlbum",
						success: () => { },
						fail: () => {
							uni.showModal({
								title: "提示",
								content: "需要您授权保存相册",
								showCancel: false,
							});
						},
					});
				}

				// uni.authorize({
				// 	scope: 'scope.userLocation',
				// 	success: () => {

				// 	},
				// 	fail: () => {
				// 		uni.showModal({
				// 			title: '提示',
				// 			content: '需要地址位置权限',
				// 			showCancel: false
				// 		});
				// 	}
				// });
			},
		});
	},
	onShow() {
		//this.getbluestatus();
		this.wifissid = uni.getStorageSync("ssid");
		this.getWifiInfo();
	},
	onLoad(options) {
		this.isbu = false
		if (options.img) {
			this.imageSrc = options.img;
			this.initImage(options.img);
		} else {
			uni.setStorageSync("devip", "");
			uni.setStorageSync("devid", "");
		}
		this.getbluestatus();
	},
	methods: {
		getWifiInfo() {
			console.log("开始初始化wifi========》");
			const _that = this;
			uni.startWifi({
				success(res) {
					console.log("初始化wifi成功:" + JSON.stringify(res));
					uni.getConnectedWifi({
						success(res) {
							console.error("获取wifi信息成功:" + JSON.stringify(res));
							console.log(res.wifi.SSID);
							_that.wifiInfo.ssid = res.wifi.SSID;
						},
						fail(res) {
							console.error("获取wifi信息失败:" + JSON.stringify(res));
							switch (res.errCode) {
								case 12000:
									_that.startWifiError = "未先调用 startWifi 接口";
									break;
								case 12001:
									_that.startWifiError = "当前系统不支持相关能力";
									break;
								case 12002:
									_that.startWifiError = "密码错误";
									break;
								case 12005:
									_that.startWifiError = "Android 特有，未打开 Wi-Fi 开关";
									break;
								case 12012:
									_that.startWifiError =
										"系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试，仅 Android 支持";
									break;
							}
						},
					});
				},
				fail(res) {
					console.error("初始化wifi失败:" + JSON.stringify(res));
				},
			});
		},
		updateHeight() {
			if (this.updatingField !== "height") {
				this.updatingField = "width";
				this.ish = (
					(this.isk / this.imgSize.width) *
					this.imgSize.height
				).toFixed(0);
			}
			this.updatingField = "";
		},
		updateWidth() {
			if (this.updatingField !== "width") {
				this.updatingField = "height";
				this.isk = (
					(this.ish / this.imgSize.height) *
					this.imgSize.width
				).toFixed(0);
			}
			this.updatingField = "";
		},
		proportionalcalculation() {
			//this.imgSize
			this.$refs.popup1.open();
		},
		gblink() {
			this.isbu = false
			Blue.closeBLEConnection();
			uni.setStorageSync("bluename", "");
			// uni.setStorageSync('ssid', "");
			// uni.setStorageSync('password', "");
			uni.setStorageSync("devip", "");
			uni.setStorageSync("devid", "");
			this.getbluestatus();
		},
		getbluestatus() {
			this.bluename = uni.getStorageSync("bluename");
			this.wifissid = uni.getStorageSync("ssid");
			var devip = uni.getStorageSync("devip");
			var devid = uni.getStorageSync("devid");
			if (devip && devid) {
				this.$set(this.linkname, "name", "WiFi模式连接中" + this.bluename);
			} else if (this.isbu && Blue.bleConnectDeviceID) {
				this.$set(this.linkname, "name", "蓝牙模式连接中" + this.bluename);
			} else {
				this.$set(this.linkname, "name", "需先点这里连接影描机");
			}
			this.isbu = true
		},
		selecttype() {
			this.startBlue(true)
			//this.$refs.popup.open();
		},
		showPopup() {
			this.$refs.popup.open();
		},
		closePopup() {
			this.$refs.popup.close();
			this.getbluestatus();
		},
		startBlue(ty) {
			console.log(ty, "aaaaaaaaaaaaaaa");
			this.closePopup();
			this.showBlueLinkDialog = true;
			this.istype = ty;
		},
		handleTouchStart(event) {
			if (event.touches.length === 1) {
				this.isDragging = true;
				this.isScaling = false; // 确保重置缩放状态
				this.touchStartX = event.touches[0].clientX;
				this.touchStartY = event.touches[0].clientY;
				this.lastMoveTime = new Date().getTime();
			} else if (event.touches.length === 2) {
				this.isScaling = true;
				this.isDragging = false; // 确保重置拖动状态
				this.touchStartPoint1 = {
					x: event.touches[0].clientX,
					y: event.touches[0].clientY,
				};
				this.touchStartPoint2 = {
					x: event.touches[1].clientX,
					y: event.touches[1].clientY,
				};
				this.touchStartDist = this.calculateDistance(
					this.touchStartPoint1,
					this.touchStartPoint2
				);
				this.touchStartScale = this.touchCurrentScale;
				this.lastMoveTime = new Date().getTime();
			}

			//console.log('Touch Start:', event.touches.length, 'touches');
			//console.log('Is Dragging:', this.isDragging, 'Is Scaling:', this.isScaling);
		},

		handleTouchMove(event) {
			if (this.isDragging) {
				this.touchMoveX = event.touches[0].clientX;
				this.touchMoveY = event.touches[0].clientY;
				// 计算手指移动的位移
				const deltaX = Math.floor(this.touchMoveX - this.touchStartX);
				const deltaY = Math.floor(this.touchMoveY - this.touchStartY);
				// 更新图像的位置
				// console.log('left',this.imgSize.left)
				// console.log('deltaX',deltaX)
				this.imgSize.left += deltaX;
				this.imgSize.top += deltaY;
				// console.log('RES',this.imgSize.left)
				// console.log('RES---')
				// 使用 requestAnimationFrame 来控制绘制频率
				const currentTime = new Date().getTime();
				if (currentTime - this.lastMoveTime > 30) {
					// 大约每 16ms 渲染一次
					this.lastMoveTime = currentTime;
					// 绘制图像
					this.drawCanvas();
				}
				this.touchStartX = this.touchMoveX;
				this.touchStartY = this.touchMoveY;
			} else if (this.isScaling) {
				this.touchCurrentPoint1 = {
					x: event.touches[0].clientX,
					y: event.touches[0].clientY,
				};
				this.touchCurrentPoint2 = {
					x: event.touches[1].clientX,
					y: event.touches[1].clientY,
				};
				this.touchCurrentDist = this.calculateDistance(
					this.touchCurrentPoint1,
					this.touchCurrentPoint2
				);
				this.scaleMultiplier = this.touchCurrentDist / this.touchStartDist;
				this.touchCurrentScale = this.touchStartScale * this.scaleMultiplier;
				const currentTime = new Date().getTime();
				if (currentTime - this.lastMoveTime > 30) {
					// 大约每 16ms 渲染一次
					this.lastMoveTime = currentTime;
					// 绘制图像
					this.drawCanvas();
				}
			}
		},

		handleTouchEnd(event) {
			this.isDragging = false;
			this.isScaling = false;
		},
		closeblue() {
			console.log("closeblue");
			this.showBlueLinkDialog = false;
			this.getbluestatus();
		},
		calculateDistance(point1, point2) {
			return Math.sqrt(
				Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2)
			);
		},
checkImage() {
	uni.chooseImage({
		count: 1,
		success: (res) => {
			// 显示加载提示
			uni.showLoading({
				title: '图片检测中...'
			});
			// 调用图片安全检测API
			const originalFilePath = res.tempFilePaths[0];
			console.log('选择的原始图片路径:', originalFilePath);
			
			// 先压缩图片用于安全检测
			this.$refs.helangCompress.compress({
				src: originalFilePath,
				maxSize: 800, // 压缩到800px以内确保文件小于1M
				fileType: 'jpg',
				quality: 0.7, // 降低质量确保文件大小
				minSize: 100
			}).then((compressedPath) => {
				console.log('压缩后的图片路径:', compressedPath);
				
				// 获取压缩后文件信息
				uni.getFileInfo({
					filePath: compressedPath,
					success: (fileInfo) => {
						console.log('压缩后文件信息:', fileInfo);
						console.log('文件大小:', (fileInfo.size / 1024 / 1024).toFixed(2) + 'MB');
						
						// 使用压缩后的图片进行安全检测
						uni.uploadFile({
							url: 'https://www.yingmiao.fun/api/upload/securityCheck',
							filePath: compressedPath,
							name: 'file',
							success: (uploadRes) => {
								uni.hideLoading();
								console.log('上传成功，返回数据:', uploadRes.data);
								const result = JSON.parse(uploadRes.data);

								if (result.code === 0) {
									// 图片检测通过，使用原始图片路径
									this.isFirstInit = true;
									this.canvasRadio = 0;
									this.rotateX = 0;
									this.rotateY = 0;
									this.rotateAll = 0;
									this.touchCurrentScale = 1;
									this.imgSize.left = 0;
									this.imgSize.top = 0;
									// 使用原始图片路径，保持图片质量
									this.ggggurl = originalFilePath;
									this.imageSrc = originalFilePath;
									this.initImage(originalFilePath);
								} else {
									// 图片检测不通过
									uni.showModal({
										title: '提示',
										content: result.msg || '图片包含敏感内容，请重新选择',
										showCancel: false
									});
								}
							},
							fail: (err) => {
								uni.hideLoading();
								console.error('上传失败:', err);
								uni.showModal({
									title: '提示',
									content: '图片检测失败，请重试: ' + JSON.stringify(err),
									showCancel: false
								});
							}
						});
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('获取压缩后文件信息失败:', err);
						uni.showModal({
							title: '提示',
							content: '获取文件信息失败: ' + JSON.stringify(err),
							showCancel: false
						});
					}
				});
			}).catch((compressErr) => {
				uni.hideLoading();
				console.error('图片压缩失败:', compressErr);
				uni.showModal({
					title: '提示',
					content: '图片压缩失败，请重试',
					showCancel: false
				});
			});
		},
		fail: (err) => {
			console.error('选择图片失败:', err);
			// uni.showModal({
			// 	title: '提示',
			// 	content: '选择图片失败: ' + JSON.stringify(err),
			// 	showCancel: false
			// });
		}
	});
},
		checkImage1() {
			uni.chooseImage({
				count: 1,
				success: (res) => {
					this.isFirstInit = true;
					this.canvasRadio = 0;
					this.rotateX = 0;
					this.rotateY = 0;
					this.rotateAll = 0;
					this.touchCurrentScale = 1;
					this.imgSize.left = 0;
					this.imgSize.top = 0;
					this.ggggurl = res.tempFilePaths[0];
					this.imageSrc = res.tempFilePaths[0];
					this.initImage(res.tempFilePaths[0]);
				},
			});
		},
		resetImage() {
			this.isFilterBlack = false;
			this.isFirstInit = true;
			this.canvasRadio = 0;
			this.rotateX = 0;
			this.rotateY = 0;
			this.rotateAll = 0;
			this.touchCurrentScale = 1;
			this.imgSize.left = 0;
			this.imgSize.top = 0;
			this.initImage(this.imageSrc);
		},

		saveCanvas(onSaveSuccess, isBgBlack = true) {
			const that = this;
			if (
				this.imageSrc === undefined ||
				this.imageSrc === null ||
				this.imageSrc === ""
			) {
				this.$modal.msgError("请先选择一张图片");
				return;
			}
			// 创建离屏canvas
			return new Promise((resolve, reject) => {
				// 把图片画到离屏 canvas 上
				const offCanvas = uni.createOffscreenCanvas({
					type: "2d",
					width: this.canvasStyle.width,
					height: this.canvasStyle.height,
				});
				const offCtx = offCanvas.getContext("2d");
				// 填充黑色背景
				if (isBgBlack) {
					offCtx.fillStyle = "black";
					offCtx.fillRect(0, 0, this.canvasStyle.width, this.canvasStyle.height);
				}
				// 将主canvas的内容绘制到离屏canvas
				offCtx.drawImage(canvas, 0, 0);

				// 将 canvas 转为临时文件
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: this.canvasStyle.width,
					height: this.canvasStyle.height,
					destWidth: this.canvasStyle.width,
					destHeight: this.canvasStyle.height,
					quality: 1,
					canvas: offCanvas,
					success(res) {
						console.log(res);
						if (onSaveSuccess) {
							onSaveSuccess(res);
						}
					},
					fail(err) {
						that.$modal.msgError("图片生成失败");
						console.error(err);
					},
				},
					that
				);
			});
		},
		//恢复图片大小至全屏
		resizeImage() {
			this.touchCurrentScale = 1;
			this.isFirstInit = true;
			this.canvasRadio = 0;
			this.imgSize.left = 0;
			this.imgSize.top = 0;
			this.drawCanvas();
		},
		toCorrectionPage() {
			// this.$tab.navigateTo(`/pages/sendCorrectionImage?img=${this.imageSrc}`)
			var that = this;

			if (this.imageSrc === undefined || this.imageSrc === null || this.imageSrc === "") {
				this.$modal.msgError("请先选择一张图片")
				return
			}



			uni.authorize({
				scope: "scope.writePhotosAlbum",
				success(vrs) {
					console.log(vrs);
				},
				fail(err) {
					console.log(err);
				},
				complete(complete) {
					console.log(complete);
				},
			});

			if (this.isSending1) {
				console.log("Button is currently disabled.");
				return;
			}
			console.log("Sending started.");
			this.isSending1 = true;

			this.resizeImage();
			if (this.rotateAll === 90 || this.rotateAll === 270) {
				const originalRatio = Math.min(
					this.canvasStyle.width / this.imageInfo.width,
					this.canvasStyle.height / this.imageInfo.height
				);

				const rotatedRatio = Math.min(
					this.canvasStyle.width / this.imageInfo.height,
					this.canvasStyle.height / this.imageInfo.width
				);
				const ratio = rotatedRatio / originalRatio
				this.scaleImage(ratio);
			}

			setTimeout(() => {
				// 假设 imgSize 包含图片在 canvas 中的实际位置和尺寸
				const {
					left,
					top,
					width,
					height
				} = this.imgSize;
				var disWidth = this.rotateAll === 90 || this.rotateAll === 270 ? height : width
				var disHight = this.rotateAll === 90 || this.rotateAll === 270 ? width : height
				// 创建一个新的 canvas
				const offCanvas = uni.createOffscreenCanvas({
					type: "2d",
					width: disWidth,
					height: disHight,
				});
				const offCtx = offCanvas.getContext("2d");

				// 从原始 canvas 中提取图片数据
				var disLeft = this.rotateAll === 90 || this.rotateAll === 270 ? (this.canvasStyle.width - disWidth) / 2 : left
				var disTop = this.rotateAll === 90 || this.rotateAll === 270 ? (this.canvasStyle.height - disHight) / 2 : top
				const imageData = ctx.getImageData(disLeft, disTop, disWidth, disHight);
				console.log(disLeft, disTop, disWidth, disHight)
				// 将图片数据绘制到新的 canvas 上
				offCtx.putImageData(imageData, 0, 0);

				// 将新 canvas 的内容转换为临时文件路径
				uni.canvasToTempFilePath({
					canvas: offCanvas,
					success: (res) => {
						const tempFilePath = res.tempFilePath;
						// 保存图片到相册
						this.$tab.navigateTo(
							`/pages/sendCorrectionImage?img=${tempFilePath}`
						);
					},
					fail: (err) => {
						console.error("获取 canvas 内容失败", err);
					},
				});
			}, 500);
			setTimeout(() => {
				this.isSending1 = false; // Re-enable the button after 2 seconds
				console.log("Sending enabled again.");
			}, 2000);
		},
		saveImage() {
			const that = this;
			uni.authorize({
				scope: "scope.writePhotosAlbum",
				success(vrs) {
					console.log(vrs);
				},
				fail(err) {
					console.log(err);
				},
				complete(complete) {
					console.log(complete);
				},
			});

			this.resizeImage();
			if (this.rotateAll === 90 || this.rotateAll === 270) {
				const originalRatio = Math.min(
					this.canvasStyle.width / this.imageInfo.width,
					this.canvasStyle.height / this.imageInfo.height
				);

				const rotatedRatio = Math.min(
					this.canvasStyle.width / this.imageInfo.height,
					this.canvasStyle.height / this.imageInfo.width
				);
				const ratio = rotatedRatio / originalRatio
				this.scaleImage(ratio);
			}

			setTimeout(() => {
				// 假设 imgSize 包含图片在 canvas 中的实际位置和尺寸
				const {
					left,
					top,
					width,
					height
				} = this.imgSize;
				var disWidth = this.rotateAll === 90 || this.rotateAll === 270 ? height : width
				var disHight = this.rotateAll === 90 || this.rotateAll === 270 ? width : height
				// 创建一个新的 canvas
				const offCanvas = uni.createOffscreenCanvas({
					type: "2d",
					width: disWidth,
					height: disHight,
				});
				const offCtx = offCanvas.getContext("2d");

				// 从原始 canvas 中提取图片数据
				var disLeft = this.rotateAll === 90 || this.rotateAll === 270 ? (this.canvasStyle.width - disWidth) / 2 : left
				var disTop = this.rotateAll === 90 || this.rotateAll === 270 ? (this.canvasStyle.height - disHight) / 2 : top
				const imageData = ctx.getImageData(disLeft, disTop, disWidth, disHight);
				console.log(disLeft, disTop, disWidth, disHight)
				// 将图片数据绘制到新的 canvas 上
				offCtx.putImageData(imageData, 0, 0);

				// 将新 canvas 的内容转换为临时文件路径
				uni.canvasToTempFilePath({
					canvas: offCanvas,
					success: (res) => {
						const tempFilePath = res.tempFilePath;
						uni.saveImageToPhotosAlbum({
							filePath: tempFilePath,
							success(resuss) {
								console.log(resuss, "图片已成功保存到相册");
								that.$modal.msgSuccess("图片已成功保存到相册");
							},
							fail(err) {
								that.$modal.msgError("图片保存失败");
							},
						});
					},
					fail: (err) => {
						console.error("获取 canvas 内容失败", err);
					},
				});
			}, 500);

		},
		sendImage() {
			if (!Blue.bleConnectDeviceID) {
				uni.showToast({
					title: "请先连接影描机",
					icon: "none",
				});
				return;
			}

			if (this.isSending) {
				console.log("Button is currently disabled.");
				return;
			}
			console.log("Sending started.");
			this.isSending = true;

			this.saveCanvas((res) => {
				console.log(res, "savecanvasres");
				const path = res.tempFilePath;
				// 单张压缩
				this.$refs.helangCompress
					.compress({
						src: path,
						maxSize: 1000,
						fileType: "jpg",
						quality: 1,
						minSize: 100, //最小压缩尺寸，图片尺寸小于该时值不压缩，非H5平台有效。若需要忽略该设置，可设置为一个极小的值，比如负数。
					})
					.then((res) => {
						// 压缩成功回调
						//console.log(res, "从canvas中提取后再压缩后的图片")
						var devip = uni.getStorageSync("devip");
						var devid = uni.getStorageSync("devid");
						if (devip && devid) {
							console.log("发现了设备IP和设备ID 使用WIFI模式传送");
							console.log("IP WIFI名", devip, devid);
							console.log("http://" + devip + "/playimg");
							var klurl = "http://" + devip + "/playimg";
							uni.uploadFile({
								url: klurl, // 上传的接口地址
								filePath: res,
								name: "file",
								formData: {
									user: "test",
								},
								success: function (res) {
									console.log(res.data); // 上传成功后的响应数据
								},
								fail: function (error) {
									// 处理上传失败的错误
									console.error("上传失败", error);
									if (error.errMsg.includes("net::ERR_CONNECTION")) {
										// 网络错误处理
										console.log("网络连接问题，请检查网络连接");
									} else if (error.errMsg.includes("404")) {
										// 服务器端错误处理
										console.log("服务器未找到上传地址");
									} else {
										// 其他错误处理
										console.log("其他错误：", error);
									}
								},
							});
						} else {
							console.log("使用蓝牙模式传送");
							Blue.readFile(res, (buffer) => {
								Blue.sendBinaryFile(buffer);
							});
						}
					})
					.catch((err) => {
						console.log(err);
						uni.showToast({
							title: "图片压缩失败",
							icon: "none",
						});
						this.isSending = false; // Re-enable the button after 2 seconds
						// 压缩失败回调
					});
			});
			setTimeout(() => {
				this.isSending = false; // Re-enable the button after 2 seconds
				console.log("Sending enabled again.");
			}, 2000);
		},
		saveBase64ToImage(base64Data) {
			// 获取文件系统管理器
			const fs = uni.getFileSystemManager();
			// 指定文件保存的路径，这里使用临时文件路径
			const filePath = `${uni.env.USER_DATA_PATH}/temp_image_${Date.now()}.png`;
			// 将 Base64 字符串转换为 ArrayBuffer
			const buffer = uni.base64ToArrayBuffer(base64Data.split(",")[1]);
			// 写入文件
			fs.writeFile({
				filePath: filePath,
				data: buffer,
				encoding: "binary",
				success: (res) => {
					console.log("文件保存成功:", filePath);
					this.initImage(filePath, false);
				},
				fail: (err) => {
					console.error("文件保存失败:", err);
				},
			});
		},
		gotoxiangao() {
			canvas2data = ctx2.getImageData(0, 0, canvas.width, canvas.height);
			console.log("先把canvas2data数据保存起来");
			uni.showLoading({
				title: "生成中...",
			});

			var that = this;

			uni.uploadFile({
				url: "https://www.yingmiao.fun/a.php", // 上传的接口地址
				filePath: that.ggggurl,
				name: "file",
				formData: {
					user: "test",
				},
				success: function (res) {
					that.saveBase64ToImage(res.data);
					uni.hideLoading();
				},
				fail: function (error) {
					uni.hideLoading();
					// 处理上传失败的错误
					console.error("上传失败", error);
					if (error.errMsg.includes("net::ERR_CONNECTION")) {
						// 网络错误处理
						console.log("网络连接问题，请检查网络连接");
					} else if (error.errMsg.includes("404")) {
						// 服务器端错误处理
						console.log("服务器未找到上传地址");
					} else {
						// 其他错误处理
						console.log("其他错误：", error);
					}
				},
			});
		},
		async initImage(url, isLoadCanvas2 = true) {
			this.imageInfo = await this.getImageInfo(url);
			this.ggggurl = this.imageInfo.path;
			console.log("imageInfo", JSON.stringify(this.imageInfo));
			if (!this.imageInfo.path) return;
			await new Promise((resolve) => {
				this.$nextTick(() => {
					setTimeout(() => {
						resolve();
					}, 200);
				});
			});
			let canvasSq = await new Promise((resolve) => {
				uni
					.createSelectorQuery()
					.in(this)
					.select("#imageCanvas")
					.boundingClientRect()
					.exec((rect) => {
						delete rect[0].dataset;
						resolve(rect[0]);
					});
			});
			canvas = await new Promise((resolve) => {
				uni
					.createSelectorQuery()
					.in(this)
					.select("#imageCanvas")
					.fields({
						node: true,
						size: true,
					})
					.exec((res) => {
						resolve(res[0].node || res[0]);
					});
			});

			// canvas.width = canvasSq.width * dpr;
			// canvas.height = canvasSq.height * dpr;
			canvas.width = this.canvasStyle.width;
			canvas.height = this.canvasStyle.height;
			ctx = canvas.getContext("2d");

			this.canvasRadio = canvas.width / this.canvasStyle.width;
			console.log("canvas.width", canvas.width);
			console.log("canvas.height", canvas.height);
			console.log("radio", this.canvasRadio);
			ctx.scale(this.canvasRadio, this.canvasRadio);

			if (isLoadCanvas2) {
				canvas2 = await new Promise((resolve) => {
					uni
						.createSelectorQuery()
						.in(this)
						.select("#imageCanvasHide")
						.fields({
							node: true,
							size: true,
						})
						.exec((res) => {
							resolve(res[0].node || res[0]);
						});
				});
				canvas2.width = canvas.width;
				canvas2.height = canvas.height;
				ctx2 = canvas2.getContext("2d");
				ctx2.scale(this.canvasRadio, this.canvasRadio);
			}
			await this.drawCanvas(isLoadCanvas2);
		},
		async drawCanvas(isLoadCanvas2 = true) {
			let that = this;
			let imgSize = {};
			//计算图片缩放比例 (ratio) 以适应画布宽度


			const ratio = Math.min(
				this.canvasStyle.width / this.imageInfo.width,
				this.canvasStyle.height / this.imageInfo.height
			);

			// 计算图片缩放比例 (ratio) 以适应画布宽度

			const firstLeft = this.isFirstInit ?
				(this.canvasStyle.width - this.imageInfo.width * ratio) / 2 :
				0;
			const firstTop = this.isFirstInit ?
				(this.canvasStyle.height - this.imageInfo.height * ratio) / 2 :
				0;
			this.isFirstInit = false;
			imgSize = {
				left: firstLeft + this.imgSize.left,
				top: firstTop + this.imgSize.top,
				width: this.imageInfo.width * ratio * this.touchCurrentScale,
				height: this.imageInfo.height * ratio * this.touchCurrentScale,
			};
			this.imgSize = imgSize;
			console.log("imgSize", JSON.stringify(this.imgSize));

			await new Promise((resolve, reject) => {
				image = canvas.createImage();
				image.onload = () => {
					resolve();
				};
				image.src = that.imageInfo.path;
			});

			ctx.clearRect(0, 0, canvas.width, canvas.height);
			const rotateAllRadians = (this.rotateAll * Math.PI) / 180;
			// 根据旋转条件绘制图片
			this.drawImageWithRotation(
				ctx,
				image,
				imgSize,
				rotateAllRadians,
				this.rotateX,
				this.rotateY
			);
			imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);

			if (isLoadCanvas2) {
				await new Promise((resolve, reject) => {
					image2 = canvas2.createImage();
					image2.onload = () => {
						resolve();
					};
					image2.src = that.imageInfo.path;
				});
				ctx2.clearRect(0, 0, canvas.width, canvas.height);
				ctx2.drawImage(
					image,
					imgSize.left,
					imgSize.top,
					imgSize.width,
					imgSize.height
				);
				imgData2 = ctx2.getImageData(0, 0, canvas.width, canvas.height);
			}

			if (this.isFilterBlack) {
				const data = imgData.data;
				for (let i = 0; i < data.length; i += 4) {
					let r = data[i];
					let g = data[i + 1];
					let b = data[i + 2];
					let average = Math.floor((r + g + b) / 3);
					data[i] = average;
					data[i + 1] = average;
					data[i + 2] = average;
				}
				ctx.putImageData(imgData, 0, 0);
			}
		},

		/**
		 * 根据旋转条件绘制图片
		 * */
		drawImageWithRotation(
			ctx,
			image,
			imgSize,
			rotateAllRadians,
			rotateX,
			rotateY
		) {
			ctx.save();

			//新加
			ctx.fillStyle = "black";
			ctx.fillRect(0, 0, this.canvasStyle.width, this.canvasStyle.height);

			ctx.translate(
				imgSize.left + imgSize.width / 2,
				imgSize.top + imgSize.height / 2
			);
			ctx.rotate(rotateAllRadians);
			ctx.translate(
				-(imgSize.left + imgSize.width / 2),
				-(imgSize.top + imgSize.height / 2)
			);

			if (rotateY === 180 && rotateX === 180) {
				ctx.translate(
					imgSize.left + imgSize.width,
					imgSize.top + imgSize.height
				);
				ctx.scale(-1, -1);
			} else if (rotateY === 180) {
				ctx.translate(imgSize.left, imgSize.top + imgSize.height);
				ctx.scale(1, -1);
			} else if (rotateX === 180) {
				ctx.translate(imgSize.left + imgSize.width, imgSize.top);
				ctx.scale(-1, 1);
			} else {
				ctx.translate(imgSize.left, imgSize.top);
			}

			ctx.drawImage(image, 0, 0, imgSize.width, imgSize.height);
			ctx.restore();
		},

		/**
		 *垂直反转
		 * */
		rotateTopButtom() {
			if (
				this.imageSrc === undefined ||
				this.imageSrc === null ||
				this.imageSrc === ""
			) {
				this.$modal.msgError("请先选择一张图片");
				return;
			}
			this.rotateY = 180 - this.rotateY;
			this.drawCanvas();
		},
		/**
		 * 水平翻转
		 * */
		rotateLeftRight() {
			if (
				this.imageSrc === undefined ||
				this.imageSrc === null ||
				this.imageSrc === ""
			) {
				this.$modal.msgError("请先选择一张图片");
				return;
			}
			this.rotateX = 180 - this.rotateX;
			this.drawCanvas();
		},
		/**
		 * 旋转
		 * */
		rotateRight(num) {
			if (
				this.imageSrc === undefined ||
				this.imageSrc === null ||
				this.imageSrc === ""
			) {
				this.$modal.msgError("请先选择一张图片");
				return;
			}
			let rotate = this.rotateAll + num;
			if (rotate < 0) {
				rotate += 360;
			}
			this.rotateAll = rotate % 360;
			const originalRatio = Math.min(
				this.canvasStyle.width / this.imageInfo.width,
				this.canvasStyle.height / this.imageInfo.height
			);

			const rotatedRatio = Math.min(
				this.canvasStyle.width / this.imageInfo.height,
				this.canvasStyle.height / this.imageInfo.width
			);

			const isRotated = this.rotateAll === 90 || this.rotateAll === 270;
			const ratio = isRotated ? rotatedRatio / originalRatio : originalRatio / rotatedRatio;


			this.scaleImage(ratio);

		},
		/**
		 * 获取图片信息
		 * */
		async getImageInfo(url) {
			let info = {};
			if (url.startsWith("http"))
				url = await new Promise((resolve, reject) => {
					uni.downloadFile({
						url,
						success(e) {
							resolve(e.tempFilePath);
						},
						fail(err) {
							url = "";
							console.error("下载图片失败", err);
						},
					});
				});
			if (!url) return;
			info = await new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: url,
					success(info) {
						resolve(info);
					},
					fail(err) {
						console.error("获取图片失败", err);
					},
				});
			});
			return info;
		},
		/**
		 * 重置ImgData
		 * */
		resetImgData() {
			if (
				this.imageSrc === undefined ||
				this.imageSrc === null ||
				this.imageSrc === ""
			) {
				this.$modal.msgError("请先选择一张图片");
				return;
			}
			// if (canvas2data) {
			// 	console.log("有有有有canvas2data")

			// 	ctx.putImageData(canvas2data, 0, 0);
			// 	ctx2.putImageData(canvas2data, 0, 0);

			// 	ctx.drawImage(canvas2, 0, 0);
			// 	ctx2.drawImage(canvas2, 0, 0);
			// } else {

			// 	var ctx2imgData = ctx2.getImageData(0, 0, canvas.width, canvas.height);
			// 	ctx.putImageData(ctx2imgData, 0, 0)

			// }
			imgData = ctx2.getImageData(0, 0, canvas.width, canvas.height);
			ctx.putImageData(imgData, 0, 0);
		},

		resetCanvas() {
			this.isFirstInit = true;
			this.canvasRadio = 0;
			this.rotateX = 0;
			this.rotateY = 0;
			this.rotateAll = 0;
			this.touchCurrentScale = 1;
			this.imgSize.left = 0;
			this.imgSize.top = 0;
			this.isFilterBlack = false;
			this.drawCanvas();
		},

		scaleImage(scaleRatio) {
			// 计算当前中心点
			const centerX = this.imgSize.left + this.imgSize.width / 2;
			const centerY = this.imgSize.top + this.imgSize.height / 2;

			// 缩放尺寸
			this.imgSize.width *= scaleRatio;
			this.imgSize.height *= scaleRatio;

			// 重新计算left和top以保持中心点不变
			this.imgSize.left = centerX - this.imgSize.width / 2;
			this.imgSize.top = centerY - this.imgSize.height / 2;

			// 更新当前缩放比例（用于记录总体缩放状态）
			this.touchCurrentScale *= scaleRatio;

			// 重新绘制画布
			this.drawCanvas();
		},
		/**
		 * 滤镜处理
		 * */
		selectFilters(type) {
			if (
				this.imageSrc === undefined ||
				this.imageSrc === null ||
				this.imageSrc === ""
			) {
				this.$modal.msgError("请先选择一张图片");
				return;
			}
			switch (type) {
				case "1": //黑白
					this.isFilterBlack = !this.isFilterBlack;
					this.drawCanvas();
					break;
				case "2": //上下翻转
					this.rotateTopButtom();
					break;
				case "3": //左右翻转
					this.rotateLeftRight();
					break;
				case "5": //放大
					this.scaleImage(1.1);
					break;
				case "4": //缩小
					this.scaleImage(0.9);
					break;
				case "6": //线稿
					this.gotoxiangao();
					break;

				default:
					break;
			}
		},

		resetFileTranse() {
			Blue.onResetFileTranse();
		},
	},
};
</script>

<style lang="scss">
.sending {
	color: #fff;
	background-color: red !important;
}

.titlebor6 {
	border: 1px solid #000;
	display: inline-block;
	border-radius: 6px;
	margin-right: 10px;
}

.canvasBox {
	width: 750rpx;
  height: 421.875rpx;  /* 修改了这一行 */
	flex: 1;
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
}

.title600 {
	text-align: center;
	font-size: 30px;
	font-weight: 600;
	margin-top: 10rpx;
}

.h-300 {
	height: 340rpx;
}

page {
	background: #fff;
}

.imageCanvas {
	width: 100%;
	height: 100%;
	max-width: 100%;
	max-height: 100%;
	z-index: 2;
	background: black;
}

.canvasHide {
	z-index: 1;
	opacity: 0;
	position: absolute;
	top: -2000px;
	left: -2000px;
	transform: initial;
}

.btn {
	width: 150rpx;
	margin: 10rpx;
	height: 70rpx;
	background-color: #fff;
	border-radius: 10rpx;
	border: black 1px solid;
	line-height: 70rpx;
	font-size: 27rpx;
	text-align: center;
}

.connect-box {
	display: flex;
	border: black 1px solid;
	border-radius: 20rpx;
	height: 70rpx;
	margin: 15rpx 30rpx;
	overflow: hidden;
}

.connect-box-state {
	width: 150rpx;
	height: 70rpx;
	line-height: 70rpx;
	text-align: center;
	background: #f56c6c;
	//background: #67C23A;
	color: black;
}

.connect-box-x {
	width: 70rpx;
	height: 70rpx;
	line-height: 70rpx;
	text-align: center;
	color: black;
	font-weight: bold;
	border-left: black 1px solid;
	border-right: black 1px solid;
}

.connect-box-select-device {
	flex: 1;
	height: 70rpx;
	line-height: 70rpx;
	text-align: center;
	color: black;
}

.btn2 {
	width: 300rpx;
	margin: 15rpx;
	height: 80rpx;
	background-color: #fff;
	border-radius: 10rpx;
	border: black 1px solid;
	line-height: 80rpx;
	font-size: 28rpx;
	text-align: center;
}
</style>